<?php

namespace app\api\controller\second;
use fast\Random;
use app\common\controller\Api;
use think\Log;

/**
 * 二手房接口
 */
class Items extends Api
{

    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['lists','item'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = [];
    /**
     * Items模型对象
     * @var \app\admin\model\second\Items
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\SecondItems;

    }
    /**
     * 获取房源列表
     *
     * @ApiTitle    (获取房源列表)
     * @ApiSummary  (可查参数 楼盘名称newhousebuilding.building_name building_id 房主姓名customer_name 几室shi_count 几厅ting_count 第几层floor 共几层floor_total 房屋类型type_id  面积area 手机号mobile 装修decoration_id )
     * @ApiMethod   (GET)
     * @ApiRoute    (/api/second/items/lists)
     * @ApiParams   (name="search", type="string", required=false, description="模糊搜索")
     * @ApiParams   (name="offset", type="integer", required=true, description="分页偏移值,0开始")
     * @ApiParams   (name="limit", type="integer", required=true, description="分页大小，默认15，最大50")
     * @ApiParams   (name="sort", type="string", required=true, description="排序字段,如: update_time")
     * @ApiParams   (name="order", type="string", required=true, description="排序顺序,asc或desc")
     * @ApiParams   (name="filter", type="string", required=false, description="查询字段，例: {'id':'56','newhousebuilding.building_name':'漕冲批发市场'}")
     * @ApiParams   (name="op", type="string", required=false, description="查询字段，例: {'id':'=','newhousebuilding.building_name':'LIKE'}")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", sample="{'user_id':'int','user_name':'string','profile':{'email':'string','age':'integer'}}", description="扩展数据返回")
     * @ApiReturn   ({
         'code':'1',
         'msg':'返回成功',
         'data':{
            "total": 1,
            "rows": []
         }
        })
     */
    public function lists()
    {
        $sort1   = $this->request->request('sort');
        $order1  = $this->request->request('order');
        if(empty($sort1)){
            $this->error('排序字段不能为空,可使用update_time');
        }
        if(empty($order1)){
            $this->error('排序不能为空');
        }
       
        Log::info($order1);

         //当前是否为关联查询
         $this->relationSearch = true;
         //设置过滤方法
         $this->request->filter(['strip_tags']);
     
        list($where, $sort, $order, $offset, $limit) = $this->buildparams('newhousebuilding.building_name,id,newhousebuilding.areaName');
        
        $total = $this->model
            ->with(['seconddecoration','newhousebuildingtypes','newhousebuilding'])
            ->where($where)
            ->order($sort, $order)
            ->count();
        $list = $this->model
                ->with(['seconddecoration','newhousebuildingtypes','newhousebuilding'])
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                 ->select()
                ;
        // 取收藏信息
        $item_id=[];
        foreach($list as $item){
            $item_id[] = $item->id;
        }
        $fav_obj=[];
        if(!empty($item_id)){
            $fav_list = (new \app\common\model\UserFavorate)
                ->where(['user_id'=>$this->auth->id,'target'=>'二手房出售房源'])
                ->where('target_id','in',$item_id)
                ->select();
            
            foreach($fav_list as $fav){
                $fav_obj[$fav->target_id]=true;
            }
        }
  
        foreach ($list as $key=>$row) {
            $row->visible(['add_cop_id','add_time','view_level','newhousebuilding.address','newhousebuilding.areaName','newhousebuilding.building_name','build_year','building_id','customer_name','floor','floor_total','id','mem','shi_count','state','ting_count','total_price','type_id','unit_price','update_time','area','seconddecoration.decoration','newhousebuildingtypes.type_name']);
            $row->getRelation('seconddecoration')->visible(['decoration']);
        }
    
        $list = collection($list)->toArray();
        for($i=0;$i<sizeof($list);$i++){
           
            // 如果有收藏，就标志出来 
            if(array_key_exists( $list[$i]['id'],$fav_obj)){
                $list[$i]['favorate']=true;
            }else{
                $list[$i]['favorate']=false;
            }
        }
        $result = array("total" => $total, "rows" => $list);

        $this->success('查询二手房列表操作成功',$result);
    }

    /** 
    * @ApiTitle    (获取房屋类型)
    * @ApiSummary  (新房二手房通用)
    * @ApiMethod   (GET)
    * @ApiRoute    (/api/second/items//housetypes)
    * @ApiReturn   ({
         'code':'1',
         'msg':'返回成功',
         'data':{
            "total": 1,
            "rows": []
         }
        })
    */
    public function housetypes(){
        $model = new \app\common\model\HouseTypes;
        $list = $model->select();
        $list = collection($list)->toArray();
        $result = array("total" => count($list), "rows" => $list);
        $this->success('查询房屋类型操作成功',$result);
    }


    /**
     * @ApiTitle  (获取房源详情)
     * @ApiSummary (二手房使用)
     * @ApiMethod (Get)
     * @ApiRoute  (/api/second/items/item)
     * @ApiParams   (name="ids", type="string", required=false, description="房源编号")
     * @ApiReturn ({
           'code' :'1',
           'msg':'返回成功',
           'data':{
               "total":1,
               "rows":[]
           } 
      })
     */
    public function item($ids){
        $ret = $this->getSecondItem($ids);
        if($ret==null){
            $this->error('房源不存在');
        }
        // 如果没有登录，不显示手机号，楼栋号房号
        $user = $this->auth->getUser();
        if(empty($user)){
            $ret['item']['mobile']  = '登录后查看';
            $ret['item']['dong']    = '*';
            $ret['item']['shi']     = '*';
            $ret['isFavorate']=false;
        }
        else{
            $isFavorate = (new Favorates())->checkfavorate($ids);
            $ret['isFavorate'] = $isFavorate;

            if($ret['item']['view_level']==3){
                // 个人私房
                if($ret['item']['add_userid'] != $this->auth->id){
                    if(!config('site.privacy_show_fanghao')){
                        // 私房是否隐藏房号
                        $ret['item']['dong']    = '*';
                        $ret['item']['shi']     = '*';
                        $ret['item']['mobile']  = '*';
                    }
                }
            }
        }
        $this->success('查询房源详情操作成功',$ret);
    }
    
    /**
     * 查询一个房源
     */
    protected function getSecondItem($ids){
        $model = new \app\common\model\SecondItems;

        $list = $model->with('seconddecoration')->where(['mf_second_items.id'=>$ids])->select();
        if(empty($list)){
            return null;
        }
        
        $ret=['item'=>$list[0]];
        
        // TODO: 权限限制
        // 跟进信息
        $followList = \app\common\model\SecondFollow::select(['item_id'=>$ids]);
        $ret['follow'] = $followList;
        // 楼盘信息
        $buildingItem = \app\common\model\SecondBuildings::get(['id'=>$list[0]->building_id]);
        $ret['building'] = $buildingItem;
        return $ret;
    }
    /**
     * @ApiTitle  (获取楼盘详情)
     * @ApiSummary (二手房使用)
     * @ApiMethod (Get)
     * @ApiRoute  (/api/second/items//building)
     * @ApiParams   (name="ids", type="string", required=false, description="楼盘编号")
     * @ApiReturn ({
           'code' :'1',
           'msg':'返回成功',
           'data':{
               "total":1,
               "rows":[]
           } 
      })
     */
    public function building($ids){
        $buildingItem = \app\common\model\SecondBuildings::get(['id'=>$ids]);
        if(empty($buildingItem)){
            $this->error('楼盘信息不存在');
        }
        $ret['building'] = $buildingItem;
        $this->success('查询楼盘详情操作成功',$ret);
    }
   
}
